/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.aacorps.javaeal.repository.user;

import edu.aacorps.javaeal.common.UserDTO;
import edu.aacorps.javaeal.repository.BaseRepositoryBean;
import edu.aacorps.javaeal.domain.User;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;

/**
 *
 * @author Ati
 */
@Stateless
public class UserRepositoryBean extends BaseRepositoryBean<User, Long> implements UserRepository {
    
    @PersistenceContext(unitName = "edu.aacorps.javaeal_JavaEAL-ejb_ejb_1.0-SNAPSHOTPU")
    private EntityManager em;

    @Override
    protected EntityManager getEntityManager() {
        return em;
    }

    public UserRepositoryBean() {
        super(User.class);
    }

    @Override
    public User find(String userName) {
        try {
        return em.createQuery("select u from User AS u where u.userName = :username", User.class)
        .setParameter("username", userName).getSingleResult();
        } catch (NoResultException e) {
            return null;
        }
    }

    @Override
    public User toUserEntity(UserDTO userDTO) {
        User user = new User();

        user.setId(userDTO.getId());
        user.setEmail(userDTO.getEmail());
        user.setUserName(userDTO.getUserName());

        return user;
    }

    @Override
    public UserDTO toUserDTO(User user) {
        UserDTO userDTO = new UserDTO();

        userDTO.setId(user.getId());
        userDTO.setEmail(user.getEmail());
        userDTO.setUserName(user.getUserName());

        return userDTO;
    }

}
